//
//  Commond.swift
//  Biubiubiu
//
//  Created by DevWhan on 2019/5/3.
//  Copyright © 2019 DevWhan. All rights reserved.
//

import Cocoa

public func alert(title: String, window: NSWindow){
    let alert = NSAlert()
    alert.messageText = title
    alert.alertStyle = .informational
    alert.addButton(withTitle: "确定")
    alert.beginSheetModal(for: window) { (_) in
    }
}

func getInterfaces() -> [(name : String, addr: String, mac : String)] {
    
    var addresses = [(name : String, addr: String, mac : String)]()
    var nameToMac = [ String: String ]()
    
    // Get list of all interfaces on the local machine:
    var ifaddr : UnsafeMutablePointer<ifaddrs>?
    guard getifaddrs(&ifaddr) == 0 else { return [] }
    guard let firstAddr = ifaddr else { return [] }
    
    // For each interface ...
    for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
        let flags = Int32(ptr.pointee.ifa_flags)
        if let addr = ptr.pointee.ifa_addr {
            let name = String(cString: ptr.pointee.ifa_name)
            
            // Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
            if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                switch Int32(addr.pointee.sa_family) {
                case AF_LINK:
                    // Get MAC address from sockaddr_dl structure and store in nameToMac dictionary:
                    addr.withMemoryRebound(to: sockaddr_dl.self, capacity: 1) { dl in
                        dl.withMemoryRebound(to: Int8.self, capacity: 8 + Int(dl.pointee.sdl_nlen + dl.pointee.sdl_alen)) {
                            let lladdr = UnsafeBufferPointer(start: $0 + 8 + Int(dl.pointee.sdl_nlen),
                                                             count: Int(dl.pointee.sdl_alen))
                            if lladdr.count == 6 {
                                nameToMac[name] = lladdr.map { String(format:"%02hhx", $0)}.joined(separator: ":")
                            }
                        }
                    }
                case AF_INET:   //AF_INET6
                    // Convert interface address to a human readable string:
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    if (getnameinfo(addr, socklen_t(addr.pointee.sa_len),
                                    &hostname, socklen_t(hostname.count),
                                    nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                        let address = String(cString: hostname)
                        addresses.append( (name: name, addr: address, mac : "") )
                    }
                default:
                    break
                }
            }
        }
    }
    
    freeifaddrs(ifaddr)
    
    // Now add the mac address to the tuples:
    for (i, addr) in addresses.enumerated() {
        if let mac = nameToMac[addr.name] {
            addresses[i] = (name: addr.name, addr: addr.addr, mac : mac)
        }
    }
    
    return addresses
}


public func getipAddr() -> String?{
    let address = getInterfaces().filter{ $0.name == "en0"}
    guard let ipAddr = address.first?.addr else {
        print("获取IP失败")
        return nil
    }
    
    return ipAddr
}
